<?php
/**
 * @uses       Custom_Db_Table_Abstract
 * @license    trafficgeyser.com
 */

class Custom_Db_Table_Abstract extends Zend_Db_Table_Abstract
{
	protected $_userId = '';

	protected $_roleId = '';

	protected $_error = '';

	//protected $_orderField ='';

	protected $_orderType = 'ASC';
        
        

	/**
	 * Paginator instance
	 * @var object
	 */
	protected $_paginator = '';

	/**
	 * For paginator
	 * @var int
	 */
	protected $_recordsPerPage = '10';

	/**
	 * For paginator
	 * @var int
	 */
	protected $_pageNo = '1';

	/**
	 * Contains logger object for db-table
	 * @var object
	 */
	protected $_logger = '';
	
         protected function _setup()
        {
            if($this->_primary)
            {         
                $this->_orderField = $this->_primary;
            }    
            else
            {
                $this->_orderField = 'id';
                
            }    
            parent::_setup();
        }
        
	public function init()
	{
		$auth = Zend_Auth::getInstance();
		
		if($auth->hasIdentity())
		{
			$this->_roleId =  $auth->getIdentity()->role_id;
			$this->_userId =  $auth->getIdentity()->id;
		}

		$this->_logger =  Zend_Registry::get('logger');
                
               
	}

	/**
	 * Inser data into table
	 * @param array $data
	 * @return bool specially inserted id, if success
	 */
	public function insert($data)
	{
		try
		{
			if(in_array('created',$this->info(self::COLS))) $data['created'] = date('Y-m-d H:i:s');
			
			return parent::insert($data);
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
		}
	}

	/**
	 * Update record by where cluse
	 * @param array $data
	 * @param string $where sql condition
	 * @return bool
	 */
	public function update($data, $where)
	{
		try
		{
			if(in_array('modified',$this->info(self::COLS))) $data['modified'] = date('Y-m-d H:i:s');

			return parent::update($data, $where);
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
		}
	}

	/**
	 * update record by id
	 * @param array $data
	 * @param int $id
	 * @return bool
	 */
	public function updateById($data, $id)
	{
                if($this->_primary)
                {         
		$where =  $this->_primary."= " . $id;
                }
                else
                {
                    $where = "id = " . $id;
                }    
		return $this->update($data,$where);
	}

	/**
	 * Update table by foreign key
	 * @param array $data data to update
	 * @param string $name table field name
	 * @param string $value field value
	 * @return bool
	 */
	public function updateByColumn($data, $name, $value)
	{
		$where = $name." = " . $value;
		return $this->update($data,$where);
	}

	/**
	 * Set order by
	 * @param string $field db field for order by default id
	 * @param string $type order type default ASC
	 */
	public function setOrderBy($field, $type = 'ASC')
	{
		$this->_orderField = $field;
		$this->_orderType  = strtoupper($type);
	}

	/**
	 * Get order by field and type
	 * @return array
	 */
	public function getOrderBy()
	{
		return $this->_orderField." ".$this->_orderType;
	}

	/**
	 * Get data by different id
	 * @param mixed $ids  array or id seprated by comma
	 * @return array
	 */
	public function get($ids)
	{
		try
		{
			if($ids)
			{
				if(is_array($ids))
				{
					return $this->find($ids)->toArray();
				}
				else
				{
					return $this->find(explode(',',$ids))->toArray();
				}
			}
			else
			{
				return false;
			}
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}

	}

	/**
	 * Get single row by id
	 * @param int $id
	 * @parm array $fields
	 * @return return array
	 */
	public function getOne($id,  $fields = '*')
	{
		try
		{
                        if($this->_primary)
                        {         
                            return $this->getOneByColumn($this->_primary,$id,  $fields);
                        }
                        else
                        {
                            return $this->getOneByColumn('id',$id,  $fields);
                            
                        }    
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}

	}

	/**
	 * Get all data
	 * @param array $fields selected fields
	 * @return array
	 */
	public function getAll($searchKey = '', $fields = '*')
	{
            
		try
		{
			#if search key
			if($searchKey)
			{
				$where = '';
				foreach($this->info(self::COLS) as $field) $where .= $field." like '".$searchKey."%' OR ";
				$where = substr_replace($where, '', -3);
			}
			else
			{
				$where = '1=1';
			}

			$select = $this->select()
							->from($this->_name,$fields)
							->where($where)
							->order($this->getOrderBy());
			return $this->_applyPaginator($select)->toArray();
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
		
	}
	
	/**
	 * Fetch data by field name
	 * @param string $name table field name
	 * @param string $value field value
	 * @param array $fields selected fields
	 * @return mixed
	 */
	public function getByColumn($name, $value, $fields = '*')
	{
            
		try
		{
			$select = $this->select()
							->from($this->_name, $fields)
							->where($name.' = ?', $value)
							->order($this->getOrderBy());
                      	return $this->_applyPaginator($select)->toArray();
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}

	/**
	 * Fetch data by more than one field name
	 * @param string $params (field name and value associate array)
	 * array('field1'=> 'value1', 'field2' => 'value2')
	 * @param array $fields selected fields
	 * @return mixed
	 */
	public function getByColumns($params, $fields = '*')
	{
		try
		{
			$select = $this->select()
							->from($this->_name, $fields);
			foreach($params as $field => $value)
			{
				$select->where($field ."= ?", $value);
			}
				$select->order($this->getOrderBy());
			
			return $this->_applyPaginator($select)->toArray();
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}
	
	/**
	 * Fetch single data based on column name
	 * @param string $name
	 * @param string $value
	 * @param array $fields selected fields
	 * @return mixed
	 */
	public function getOneByColumn($name, $value, $fields = '*')
	{
		try
		{
			$row = $this->fetchRow($this->select()
										->from($this->_name, $fields)
										->where($name.'= ?', $value));
			if($row) return $row->toArray();
			else return false;
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}


	/**
	 * Fetch single data by more than one field name
	 * @param string $params (field name and value associate array)
	 * array('field1'=> 'value1', 'field2' => 'value2')
	 * @param array $fields selected fields
	 * @return mixed
	 */
	public function getOneByColumns($params, $fields = '*')
	{
		try
		{
			$select = $this->select()
							->from($this->_name, $fields);
			foreach($params as $field => $value)
			{
				$select->where($field ."= ?", $value);
			}
				$select->order($this->getOrderBy());

			$row = $this->fetchRow($select);
			if($row) return $row->toArray();
			else return false;
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}


	/**
	 * Set model level error message
	 * @param mixed $error
	 */
	public function setError($error)
	{
		$this->_error =  $error;
	}

	/**
	 * Get model level error message
	 * @return mixed
	 */
	public function getError()
	{
		return $this->_error;
	}

	/**
	 * Set pagination parameter
	 * @param int $recordsPerPage
	 * @param int $currentPage
	 */
	public function setPaginator($recordsPerPage, $currentPage)
	{
		$this->_pageNo = $currentPage;
		$this->_recordsPerPage = $recordsPerPage;
	}

	/**
	 * Get paginator instance
	 * @return object
	 */
	public function getPaginator()
	{
		return $this->_paginator;
	}

	/**
	 *
	 * @param <type> $select
	 * @return <type>
	 */
	protected function _applyPaginator($select)
	{
		$paginator = Zend_Paginator::factory($select);
		$paginator->setItemCountPerPage($this->_recordsPerPage);
		$paginator->setCurrentPageNumber($this->_pageNo);

		$this->_paginator = $paginator;
		
		return $paginator->getCurrentItems();
	}

	/**
	 * Delete table tow by foreign key value
	 * @param string $name table field name
	 * @param string $value field value
	 * @return bool
	 */
	public function deleteByColumn($name, $value)
	{
		$where = $name." = " . $value;
		return $this->delete($where);
	}

	/**
	 * Delete by primary key field id
	 * @param string $id 
	 * @return bool
	 */
	public function deleteById($id)
	{
                if($this->_primary)
                {
                   $where = $this->_primary."= " . $id;     
                }
                else
                {
                   $where = "id = " . $id;
                }    
		return $this->delete($where);
	}

	/**
	 * fetch single user data with user details
	 * @param int $id (primary key of user assets)
	 * @param array $fields array of fields to show
	 * @return array
	 */
	public function fetchOneByUser($id,$fields = '*')
	{
		$objUser = new User_Model_DbTable_User();
		$objProfile = new User_Model_DbTable_Profile();

		if($this->_roleId == User_Model_DbTable_Role::ADMIN_USER)
			$where = "master.id = ". $id;
		else
			$where = "master.id = ". $id." and master.user_id = ". $this->_userId;

		try
		{
			$row = $this->fetchRow($this->select()
										->setIntegrityCheck(false)
									    ->from(array('master' => $this->_name), array($fields))
									    ->join(array('user' => $objUser->_name), 'user.id = master.user_id', array('role_id as user.role',
																													'first_name as user.first_name',
																													'last_name as user.last_name',
																													'email as user.email'))
										->join(array('profile' => $objProfile->_name), 'user.id = profile.user_id', 
												array('image as user.image', 'country_id as user.countryId', 'time_zone as user.timeZone'))
										->where($where));
			if($row) return $row->toArray();
			else return false;
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}

	/**
	 * fetch all user data with user details
	 * @param int $id (primary key of user assets)
	 * @param array $fields array of fields to show
	 * @return array
	 */
	public function fetchAllByUser($user_id = null, $fields = "*" )
	{
		$objUser = new User_Model_DbTable_User();
		$objProfile = new User_Model_DbTable_Profile();
		
		if($user_id)
			$where = "master.user_id =". $user_id;
		else if($this->_roleId == User_Model_DbTable_Role::ADMIN_USER)
			$where = "1 = 1";
		else
			$where = "master.user_id =". $this->_userId;

		try
		{
			$select = $this->select()
							->setIntegrityCheck(false)
							->from(array('master' => $this->_name), array($fields))
							->join(array('user' => $objUser->_name), 'user.id = master.user_id', array('role_id', 'first_name', 'last_name', 'email'))
							->join(array('profile' => $objProfile->_name), 'user.id = profile.user_id',
									array('image as user.image', 'country_id as user.countryId', 'time_zone as user.timeZone'))
							->where($where)
							->order($this->getOrderBy());

			return $this->_applyPaginator($select)->toArray();
		}
		catch(Zend_Exception $e)
		{
			$this->setError($e->getMessage());
			return false;
		}
	}
}

?>
